import { AliyunSmgConfig , LAPSE_TIME } from '../config/config'
import { getSecond , getCode } from './common'
import { VerificationCode } from './../models'
const { accessKeyId,secretAccessKey,singName,registerTemplateCode,findPasswordTemplateCode } = AliyunSmgConfig
const SMSClient = require('@alicloud/sms-sdk')
//初始化sms_client
let smsClient = new SMSClient({accessKeyId, secretAccessKey})
/**
 * 发送验证码
 * @param {string} phone 手机号码
 * @param {string} type 验证码类型
 */
export async function _sendVerificationCode(phone,type) {
    const ctime = getSecond()
    const code  = getCode()
    const body  = {}
    await smsClient.sendSMS({
        PhoneNumbers: phone,
        SignName: singName,
        TemplateCode: registerTemplateCode,
        TemplateParam: `{"code":"${code}"}`
    }).then(function (res) {
        let {Code}=res
        if (Code === 'OK') {
            body.code = 0
        }
    }, function (err) {
        console.log('短信验证码发送失败',err)
        body.code = err.code
    })
    if(body.code == 0) {
      const verificationCode = await recordVerificationCode(phone,type,code,ctime)
      if(!verificationCode) {
        body.code = -1
      }
    }
    return body
}

export async function _checkVerificationCode(phone,type,code) {
    const now = getSecond()
    const verificationCode = await VerificationCode.findOne({where:{phone,type,code,status:1}})
    if(verificationCode) {
        return Number(verificationCode.ctime) + LAPSE_TIME >= now
    } 
    return false 
}


/**
 * 记录验证码
 * 
 * @param {any} phone 
 * @param {any} type 
 * @param {any} code 
 * @param {any} ctime 
 * @returns 
 */
async function recordVerificationCode(phone,type,code,ctime) {
    let verificationCode = await VerificationCode.findOne({where:{phone,type}})
    if(verificationCode) {
        verificationCode.code   = code
        verificationCode.ctime  = ctime
        verificationCode.status = 1
        await verificationCode.save()
    } else {
        verificationCode = await VerificationCode.create({
            phone,type,code,ctime
        })
    }
    return verificationCode
}